<template>
  <div class="contain">
    <div class="nav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/control' }">菜谱</el-breadcrumb-item>
        <el-breadcrumb-item>常见菜式</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="search">
      <h3>筛选条件</h3>
      <div class="search-details">
        <el-button type="danger" size="small">全部删除</el-button>
        <label>
          <span>搜索：</span>
          <el-input v-model="search.name" placeholder="请输入菜品名" clearable size="small"></el-input>
        </label>
        <label>
          <span>分类搜索：</span>
          <el-select v-model="search.category" placeholder="请选择分类" size="small">
            <el-option v-for="item in catelist" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </label>
        <el-button size="small"  @click="add('add')">新增</el-button>
      </div>
    </div>
    <hr>
    <el-config-provider :locale="zhCn" class="list">
      <el-table :data="pagesData" style="width: 100%" max-height="500px" @selection-change="changeId"
      :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }">
        <el-table-column type="selection" width="40" v-model="ids" />
        <el-table-column fixed prop="cook_book_image" label="菜品图片" width="160">
          <template #default="scope">
            <img :src="scope.row.cook_book_image" alt="" width="150" />
          </template>
        </el-table-column>
        <el-table-column prop="cook_book_title" label="菜品名称" width="90"></el-table-column>
        <el-table-column prop="describe" label="菜品描述" width="168"></el-table-column>
        <el-table-column prop="material" label="所需材料" width="150"></el-table-column>
        <el-table-column prop="meals" label="菜品分类" width="60"></el-table-column>
        <el-table-column prop="click_count" label="点击量" width="70"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="102"></el-table-column>
        <el-table-column prop="last_update_time" label="上次更新时间" width="110"></el-table-column>
        <el-table-column prop="user_id" label="用户id" width="70"></el-table-column>
        <el-table-column prop="user_name" label="用户名" width="70"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="add('edit', scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="delproduct([scope.row.cook_book_id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-config-provider>
    <div class="page">
      <el-config-provider :locale="zhCn">
        <el-pagination v-model:current-page="pages.current" :page-sizes="[3, 6, 9]"
          layout="total,sizes,prev, pager, next" :total="pages.pagetotal" v-model:page-size="pages.pagesize" />
      </el-config-provider>
    </div>
    <el-dialog v-model="visible" width="400px" @close="close()">
      <template #header>
        <div class="my-header">
          <h4>{{ filed === "add" ? "新增菜品信息" : "修改菜品信息" }}</h4>
          <el-form :rules="rules" :model="info" ref="formrules" label-width="100px">
            <el-form-item label="菜品名称：" prop="cook_book_title">
              <el-input class="input" v-model="info.cook_book_title" placeholder="请输入菜品" clearable size="small">
              </el-input>
            </el-form-item>
            <el-form-item label="菜品描述：" prop="describe">
              <el-input class="input" v-model="info.describe" placeholder="请输入菜品描述" type="textarea" clearable
                size="small">
              </el-input>
            </el-form-item>
            <el-form-item label="所需材料：" prop="material">
              <el-input class="input" v-model="info.material" placeholder="请输入所需材料" clearable size="small">
              </el-input>
            </el-form-item>
            <el-form-item label="菜品类别：" prop="meals">
              <el-select placeholder="请选择分类" clearable size="small" v-model="info.meals">
                <el-option v-for="item in catelist" :key="item.id" :label="item.title" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="点击量：" prop="click_count">
              <el-input-number v-model="info.click_count" :min="0" @change="handleChange" />
            </el-form-item>
            <el-form-item label="收藏量：" prop="collect_count">
              <el-input-number v-model="info.collect_count" :min="0" @change="handleChange" />
            </el-form-item>
            <el-form-item label="用户id：" prop="user_id">
              <el-select placeholder="请选择用户id" clearable size="small" v-model="info.user_id">
                <el-option v-for="items in idlist" :key="items.id" :label="items.title" :value="items.id">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="用户名：" prop="user_name">
              <el-input class="input" v-model="info.user_name" placeholder="请输入用户名" clearable size="small">
              </el-input>
            </el-form-item> -->
            <el-form-item label="菜品图片：" prop="cook_book_image">
              <el-upload class="avatar-uploader" action :http-request="uploadFile" :show-file-list="false">
                <img v-if="postImg" :src="postImg" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
          <div class="btn">
            <el-button type="success" @click="changeProduct(formrules)">确定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible" title="提示" width="30%" :before-close="handleClose">
      <span>确定删除该用户信息吗?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="ConfirmDelete">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "../tools/axios";
const product = ref([]);

const postImg = ref();

const d_id = ref();



const dialogVisible = ref(false);
const handleClose = () => {
  ElMessageBox.confirm("确定关闭这个弹窗吗?")
    .then(() => { })
    .catch(() => {
      // catch error
      dialogVisible.value = false;
    });
};
const ConfirmDelete = () => {
  dialogVisible.value = false;
  // 删除接口
  http.put("/cook/delete", {
    "cook_book_id": d_id.value
  }).then((res) => {
    getmsg();
  }).catch(err => {
    console.log(err);
  });
};
const catelist = ref([
  { id: '早餐', title: "早餐" },
  { id: '午餐', title: "午餐" },
  { id: '晚餐', title: "晚餐" },
]);
const idlist = ref([
  {id:'56001',title:'56001'},
  {id:'56002',title:'56002'},
  {id:'56003',title:'56003'},
  {id:'56004',title:'56004'},
  {id:'56029',title:'56029'},
])

const pages = ref({ current: 1, pagesize: 3, pagetotal: product.value.length });
const getmsg = () => {
  // 查询接口
  http.get("/cook/get").then((res) => {
    product.value = res.data;
    console.log(res.data);
  });
};
getmsg();
const search = ref({ name: "", category: "" });
const searchData = computed(() => {
  let arr = product.value.filter((item) => {
    return (
      item.cook_book_title.includes(search.value.name) &&
      (search.value.category ? item.meals === search.value.category : true)
    );
  });

  return JSON.parse(JSON.stringify(arr)).map((item) => {
    for (var i = 0; i < catelist.value.length; i++) {
      if (catelist.value[i].id === item.meals) {
        item.meals = catelist.value[i].title;
      }
    }
    return item;
  });
});
const pagesData = computed(() => {
  pages.value.pagetotal = searchData.value.length;
  const start = (pages.value.current - 1) * pages.value.pagesize;
  const end = pages.value.current * pages.value.pagesize;
  return searchData.value.slice(start, end);
});
const ids = ref([]);
const changeId = (value) => {
  ids.value = value.map((item) => {
    return item.id;
  });
  console.log(ids.value);
};
const delproduct = (id) => {
  dialogVisible.value = true;
  d_id.value = id;
  console.log();
};
const info = ref({});
const visible = ref(null);
const rules = ref({
  cook_book_title: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
  describe: [{ required: true, message: "请输入菜品描述", trigger: "blur" }],
  meals: [{ required: true, message: "请选择菜品分类", trigger: "blur" }],
  user_id: [{ required: true, message: "请输入用户id", trigger: "blur" }],
  user_name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
});
const formrules = ref(null);
const filed = ref("add");
const add = (str, obj) => {
  visible.value = true;
  filed.value = str;
  if (obj) {
    info.value = { ...obj };
  }
};
const close = () => {
  info.value = {};
};
const changeProduct = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if (filed.value === "add") {
        info.value.id = Date.now();
        product.value.unshift(info.value);
        // 新增接口
        http.post("/cook/add", {
          "cook_book_title": info.value.cook_book_title,
          "cook_book_image": postImg.value,
          "describe": info.value.describe,
          "material":info.value.material,
          "meals": info.value.meals,
          "click_count": info.value.click_count,
          "collect_count": info.value.collect_count,
          "user_id":info.value.user_id,
        }).then((res) => {
          if (res.code === 0) {
            // 成功新增 刷新数据
            // this.$router.go(0)
            // 调用查询接口info
            ElMessage({
              showClose: true,
              message: "添加成功",
              type: "success",
            });
            getmsg();
          }
        }).catch(err => {
          console.log(err);
        });
      } else {
        product.value = product.value.map((item) => {
          if (item.id === info.value.id) {
            console.log(info.value);
            item = info.value;
          }
          return item;
        });
        // 调用修改接口
        http.put("/cook/update", {
          "cook_book_title": info.value.cook_book_title,
          "cook_book_image": info.value.cook_book_image,
          "describe": info.value.describe,
          "material":info.value.material,
          "meals": info.value.meals,
          "click_count": info.value.click_count,
          "collect_count": info.value.collect_count,
          "user_id":info.value.user_id,
          "cook_book_id": info.value.cook_book_id,
          "cook_book_image":postImg.value
        }).then((res) => {
          if (res.code === 0) {
            // 成功新增 刷新数据
            // this.$router.go(0)
            // 调用查询接口info
            ElMessage({
              showClose: true,
              message: "修改成功",
              type: "success",
            });
            getmsg();
          }
        }).catch(err => {
          console.log(err);
        });
      }
      visible.value = false;
    } else {
      ElMessage({
        showClose: true,
        message: "请补全信息重新添加",
        type: "warning",
      });
    }
  });
};


const uploadFile = (item) => {
  let FormDatas = new FormData();
  FormDatas.append('image', item.file);
  http.post("/upload/upload", FormDatas).then(result => {
    http.get(`/upload/view/${result.data.path}`).then(res=>{
      postImg.value = "http://localhost:5000/upload/view/"+result.data.path;
    })

  })
}
</script>

<style scoped>
.search-details {
  display: flex;
}

.search-details label {
  margin-left: 30px;
  color: #999;
}

label .el-input,
label .el-select {
  margin-left: 10px;
  width: 200px;
}

label .el-select {
  margin-right: 30px;
}

.list .pic {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.page {
  display: flex;
  justify-content: end;
  margin: 20px 0;
}

.avatar-uploader {
  border: 1px solid #999;
  border-radius: 6px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.btn {
  display: flex;
  justify-content: center;
}
</style>